<template>
    <div class="app-container">
        <el-form :model="filter" size="mini">
            <el-row :gutter="10">
                <el-col :span="4">
                    <el-form-item label="所属市" label-width="60px">
                        <el-select v-model="filter.city" multiple collapse-tags placeholder="请选择（默认全选）" clearable
                            style="width: 100%;">
                            <el-option v-for="city in cities" :label="city" :value="city">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="企业性质" label-width="80px">
                        <el-cascader v-model="filter.nature" :options="natures" :props="props" collapse-tags
                            placeholder="请选择（默认全选）" clearable style="width: 100%;">
                        </el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="所属行业" label-width="80px">
                        <el-cascader v-model="filter.industry" :options="industries" :props="props" collapse-tags
                            placeholder="请选择（默认全选）" clearable style="width: 100%;">
                        </el-cascader>
                    </el-form-item>
                </el-col>
                <el-col :span="2" :offset="0" align="right">
                    <el-button type="primary" @click="display" icon="el-icon-search" size="mini">查询</el-button>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="10">
                    <el-form-item label="调查期一" label-width="80px">
                        <el-select v-model="filter.invTime1" placeholder="请选择" clearable style="width: 100%;">
                            <el-option v-for="invTime in invTimes" :label="invTime.investigationStartDate"
                                :value="invTime.investigationId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="调查期二" label-width="80px">
                        <el-select v-model="filter.invTime2" placeholder="请选择" clearable style="width: 100%;">
                            <el-option v-for="invTime in invTimes" :label="invTime.investigationStartDate"
                                :value="invTime.investigationId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="2" align="right">
                    <el-button type="info" @click="resetFilter" icon="el-icon-refresh-left" size="mini">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
        <v-chart class="chart" :option="option" autoresize />
        <div class="table">
            <el-table v-loading="listLoading" stripe :data="showData" element-loading-text="Loading" border fit
                highlight-current-row :cell-style="{ padding: '5px 0' }" :cell-class-name="classChecker">
                <el-table-column prop="invTime" label="调查期时间" align="center"></el-table-column>
                <el-table-column prop="companyCnt" label="企业总数" align="center"></el-table-column>
                <el-table-column prop="iniCnt" label="建档期就业人数" align="center"></el-table-column>
                <el-table-column prop="finCnt" label="调查期就业人数" align="center"></el-table-column>
                <el-table-column prop="decCnt" label="岗位减少总数" align="center"></el-table-column>
                <el-table-column prop="deltaCnt" label="岗位变化总数" align="center"></el-table-column>
                <el-table-column prop="changeProportion" label="岗位变化占比" align="center"></el-table-column>
            </el-table>
        </div>
    </div>
</template>
  
<script>
import { getIndustries, getNatures, getAllEnterpriseInfo, getAllFormList, getAllInvestigationInfo } from '@/api/province/dataVisualization';

import { use } from 'echarts/core'
import { BarChart } from 'echarts/charts'
import VChart, { THEME_KEY } from 'vue-echarts';
import {
    LegendComponent,
    TooltipComponent,
    ToolboxComponent,
    DatasetComponent,
    GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

use([
    LegendComponent,
    TooltipComponent,
    ToolboxComponent,
    DatasetComponent,
    GridComponent,
    BarChart,
    CanvasRenderer
])


export default ({
    provide: {
        [THEME_KEY]: 'light',
    },

    created() {
        this.listLoading = true;
        this.fetchData().then(() => {
            this.listLoading = false;
        })
    },

    components: {
        VChart,
    },

    methods: {
        resetFilter() {
            this.filter = {
                city: '',
                nature: '',
                industry: '',
                invTime1: '',
                invTime2: ''
            }
        },

        display() {
            if (this.filter.invTime1 == '' || this.filter.invTime2 == '') {
                this.$message({
                    message: "请指定两个调查期",
                    type: 'warning'
                })
                return;
            }

            
            let showCities = [];
			let showIndustries = []
			let showNatures = []
            
			if (this.filter.city.length == 0) {
                showCities = this.cities;
			} else {
                showCities = this.filter.city;
			}
            
			if (this.filter.industry.length == 0) {
                this.industries.forEach(item_first => {
                    item_first.children.forEach(item_second => {
                        showIndustries.push(item_first.value + '/' + item_second.value);
					})
				})
			} else {
                this.filter.industry.forEach(item => {
                    showIndustries.push(item.at(0) + '/' + item.at(1));
				})
			}
            
			if (this.filter.nature.length == 0) {
                this.natures.forEach(item_first => {
                    item_first.children.forEach(item_second => {
                        showNatures.push(item_first.value + '/' + item_second.value);
					})
				})
			} else {
                this.filter.nature.forEach(item => {
                    showNatures.push(item.at(0) + '/' + item.at(1));
				})
			}
            
			
			showCities = new Set(showCities)
			showIndustries = new Set(showIndustries)
			showNatures = new Set(showNatures)
            
            let filteredCompanies = new Set();
            this.companies.forEach(item => {
                if (showCities.has(item.companyCity) && showIndustries.has(item.companyIndustry) && showNatures.has(item.companyNature)) filteredCompanies.add(item.companyId);
            })

            this.showData = [{
                invId: this.filter.invTime1,
                invTime: this.invTimesMap.get(this.filter.invTime1),
                companyCnt: 0,
                iniCnt: 0,
                finCnt: 0,
                deltaCnt: 0,
                decCnt: 0,
                changeProportion: '0%'
            },
            {
                invId: this.filter.invTime2,
                invTime: this.invTimesMap.get(this.filter.invTime2),
                companyCnt: 0,
                iniCnt: 0,
                finCnt: 0,
                deltaCnt: 0,
                decCnt: 0,
                changeProportion: '0%'
            }]

            // console.log(filteredCities)
            // console.log(filteredCompanies)

            this.rawData.forEach(item => {
                if (filteredCompanies.has(item.companyId)) {
                    this.showData.forEach(element => {
                        if (item.investigationId == element.invId) {
                            element.companyCnt += 1;
                            element.iniCnt += item.formStartTotalNum;
                            element.finCnt += item.formEndTotalNum;
                            element.deltaCnt += item.formEndTotalNum - item.formStartTotalNum;
                            element.decCnt += (item.formEndTotalNum - item.formStartTotalNum < 0) ? item.formEndTotalNum - item.formStartTotalNum : 0;
                            element.changeProportion = element.iniCnt == 0 ? '无意义' : (100 * element.deltaCnt / element.iniCnt).toFixed(1) + '%';
                        }
                    })
                }
            }
            )

            this.option.dataset.source = [
                ['数目', '调查期一', '调查期二'],
                ['建档期就业人数', this.showData[0].iniCnt, this.showData[1].iniCnt],
                ['调查期就业人数', this.showData[0].finCnt, this.showData[1].finCnt],
                ['岗位变化总数', this.showData[0].deltaCnt, this.showData[1].deltaCnt],
                ['岗位减少总数', this.showData[0].decCnt, this.showData[1].decCnt]
            ]

            this.option.yAxis.show = true;
            // console.log(this.option.dataset.source)

        },


        async fetchData() {
            getAllEnterpriseInfo({}).then(response => {
                this.companies = response.data;
                this.cities = Array.from(new Set(this.companies.map(item => item.companyCity)))
                // console.log(response)
            })
            getAllInvestigationInfo({}).then(response => {
                this.invTimes = response.data;
                this.invTimes.forEach(item => {
                    this.invTimesMap.set(item.investigationId, item.investigationStartDate);
                })
                // console.log(response)
            })
            getAllFormList({ company: {}, investigationPeriod: {} }).then(response => {
                this.rawData = response.data;
                // console.log(response)
            })

        },

        classChecker({ row, column }) {
			if (column.property === 'deltaCnt' || column.property === 'changeProportion' ) {
                let val = row.deltaCnt
				if (val > 0 ) {
					return 'greenClass'
				} else if (val < 0) {
					return 'redClass'
				}
			}
			return ''
		}

    },

    data() {
        return {
            option: {
                legend: {},
                tooltip: {},
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                dataset: {
                    source: [
                        ['建档期就业人数', 0, 0],
                        ['调查期就业人数', 0, 0],
                        ['岗位变化总数', 0, 0],
                        ['岗位减少总数', 0, 0]
                    ]
                },
                xAxis: { type: 'category' },
                yAxis: { show: false },
                // Declare several bar series, each will be mapped
                // to a column of dataset.source by default.
                series: [{ type: 'bar' }, { type: 'bar' }]
            },

            cities: [],
            natures: getNatures(),
            industries: getIndustries(),
            invTimes: [],
            invTimesMap: new Map(),
            companies: [],
            rawData: [],
            filter: {
                city: '',
                nature: '',
                industry: '',
                invTime1: '',
                invTime2: ''
            },
            showData: [],
            listLoading: false,
            props: { multiple: true }
        }
    }
});
</script>
  
<style scoped>
.chart {
    height: 500px;
    width: 100%;
}
</style>

<style>
.el-table .greenClass{
	color: green;
}

.el-table .redClass{
	color: red;
}
</style>
  